package com.huatek.framework.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.huatek.framework.entity.FwDuty;
import com.huatek.framework.entity.FwSystem;
import com.huatek.framework.security.ThreadLocalClient;
import com.huatek.framework.service.OperationService;
import com.huatek.framework.service.RoleService;
import com.huatek.framework.service.SourceService;
import com.huatek.framework.service.SystemService;
import com.huatek.framework.tag.CommonBean;
import com.huatek.framework.tag.CutPageBean;
import com.huatek.framework.util.CommonUtil;
import com.huatek.framework.util.QueryCondition;
import com.huatek.framework.validate.BaseEntityEditor;
import com.huatek.framework.validate.ValidateFieldLength;

@Controller
@RequestMapping("/role.do")
@SessionAttributes(types = FwDuty.class)
public class RoleController {
	@Autowired
	private RoleService roleService;
	@Autowired
	private SourceService sourceService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private OperationService operationService;

	private String getInitDataPage(Model model){
		model.addAttribute("systemList", systemService.getAvailableFwSystem());
		return "page.duty_edit";
	}
	@RequestMapping(params = "actionMethod=add",method = RequestMethod.GET)
	public String add(Model model){
		model.addAttribute(new FwDuty());
		return getInitDataPage(model);
	}
	@RequestMapping(params = "actionMethod=add",method = RequestMethod.POST)
	public String processAdd(Model model,@ModelAttribute FwDuty duty, BindingResult result, SessionStatus status) {
		return this.processEdit(model,duty, result, status);
	}
	@RequestMapping(params = "actionMethod=edit",method = RequestMethod.GET)
	public String edit(@RequestParam("queryId") Long id,Model model){
		model.addAttribute(roleService.getRoleById(id));
		return getInitDataPage(model);
	}
	@RequestMapping(params = "actionMethod=edit",method = RequestMethod.POST)
	public String processEdit(Model model,@ModelAttribute FwDuty duty, BindingResult result, SessionStatus status){
		validate(duty, result);
		if(result.hasErrors()){
			return getInitDataPage(model);
		}
		roleService.saveRole(duty);
		status.setComplete();
		return "redirect:role.do?actionMethod=query";
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "actionMethod=delete",method = RequestMethod.POST)
	public String delete(@RequestParam("id") Long[] ids) {
		List<FwDuty> roles = roleService.findDatasByIds(FwDuty.class, ids);
		if(roles!=null&&roles.size()>0){
				roleService.deleteAll(roles);
		}
		return "redirect:role.do?actionMethod=query";
	}
	@RequestMapping(params = "actionMethod=query")
	public String query(Model model,HttpServletRequest request){
		List<CommonBean> paramterList = QueryCondition.getQueryCondition(request,FwDuty.class);
		CutPageBean pageBean = QueryCondition.getQueryPageBean(request);
		model.addAttribute("queryParams",paramterList);
		model.addAttribute("pageBean", roleService.getRolePageBean(pageBean, paramterList));
		return "page.duty_list";
	}
	@InitBinder
	protected void initBinder(WebDataBinder dataBinder) {
		dataBinder.registerCustomEditor(FwSystem.class, "fwSystem", new BaseEntityEditor(FwSystem.class));
	/*	DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		dataBinder.registerCustomEditor(Date.class, "entryDate", dateEditor);
		dataBinder.registerCustomEditor(Date.class, "approvalDate", dateEditor);
		dataBinder.registerCustomEditor(Date.class, "dimissionDate", dateEditor);*/
	}

	@RequestMapping(params = "actionMethod=assign",method = RequestMethod.GET)
	public String assignAction(@RequestParam("id") Long id,Model model){
		if(ThreadLocalClient.get().getOperator().getId().longValue()==1){//administrator
			model.addAttribute("assignSourceList", sourceService.getMenuSources());
			model.addAttribute("createGroupAction",operationService.getAllAction());
		}else{
			model.addAttribute("assignSourceList",ThreadLocalClient.get().getOperator().permitSourceList);
			//model.addAttribute("createGroupAction",ThreadLocalClient.get().getOperator().getPermitTable().get(GlobalVar.defaultGroupId));
		}
		model.addAttribute("duty",roleService.getRoleById(id));
		return "page.choose_action";
	}

	@RequestMapping(params = "actionMethod=assign",method = RequestMethod.POST)
	public String processAssignAction(@RequestParam("dutyId") Long id,@RequestParam("srcActionId") Long[] actionIds){
		roleService.assignOperation(id,actionIds);
		return "redirect:role.do?actionMethod=query";
	}

	public static void validate(FwDuty duty, Errors errors) {
		if (CommonUtil.isZeroLengthTrimString(duty.getName())) {
			errors.rejectValue("name", "required", "required");
		}
		if (CommonUtil.isZeroLengthTrimString(duty.getStatus())) {
			errors.rejectValue("status", "required", "required");
		}
		if (CommonUtil.isZeroLengthTrimString(duty.getDutyType())) {
			errors.rejectValue("dutyType", "required", "required");
		}
		if(duty.getFwSystem()==null ){
			duty.setFwSystem(new FwSystem());
		}
		if(duty.getFwSystem().isNew()){
			duty.getFwSystem().setId(Long.valueOf("1"));
		}
		ValidateFieldLength.validateMaxLength(errors, "name", 120, "maxLimitLength", "Enter overflow.");
		ValidateFieldLength.validateMaxLength(errors, "describe", 200, "maxLimitLength", "Enter overflow.");
	}
}
